package com.hice.demo.sbdbra.common.util.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;

public class MD5Util {
    private static Logger log = LoggerFactory.getLogger(MD5Util.class);

    public static String MD5(String s) {
        try {
            byte[] bInput = s.getBytes("UTF-8");

            return MD5(bInput);
        } catch (Exception e) {
            log.error("======MD5加密失败====");
        }
        return null;
    }

    public static String MD5(String s, String encoding) {
        try {
            byte[] bInput = s.getBytes(encoding);

            return MD5(bInput);
        } catch (Exception e) {
            log.error("======MD5加密失败====");
        }
        return null;
    }

    public static String MD5(byte[] bytes) {
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(bytes);
            byte[] b = md.digest();
            int j = b.length;
            char[] str = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = b[i];
                str[(k++)] = hexDigits[(byte0 >>> 4 & 0xF)];
                str[(k++)] = hexDigits[(byte0 & 0xF)];
            }
            return new String(str);
        } catch (Exception e) {
            log.error("======MD5加密失败====");
        }
        return null;
    }

    public static byte[] Md5Byte(String s) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            return md5.digest(s.getBytes("UTF-8"));
        } catch (Exception e) {
            log.error("======MD5加密失败====");
        }
        return null;
    }
}